var sqlite3 = require('sqlite3').verbose();
var config = require('../config.json');

module.exports = {
  readDict: function (callback) {
    var db = new sqlite3.Database(process.cwd() + config.store.database.dbFile);
    db.all("select content from words",function (err, data) {
      if(err) callback(err, null);
      else {
        var result = [];
        for (var i = 0; i < data.length; i++) {
          result.push(JSON.parse(data[i].content));
        }
        callback(null, result);
      }
    });
    db.close();
  },

  saveWord: function (word, object, callback) {
    var db = new sqlite3.Database(process.cwd() + config.store.database.dbFile);
    var stmt = db.prepare("UPDATE words SET scale=?,content=?,phonetic=? where word=?");
    stmt.all(object.scale, JSON.stringify(object), object.phonetic.default, object.word, function (err) {
      callback(err);
    });
    stmt.finalize();
    db.close();
  }
};